package com.colzry.mybatisplus.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.colzry.mybatisplus.entity.User;
import com.colzry.mybatisplus.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;


@Controller
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping("/user")
    public User getUserById(@RequestParam("id") int id) {
        return userService.getById(id);
    }

    @RequestMapping("/")
    public String getIndexPage(@RequestParam(value = "pn", defaultValue = "1") Integer pn,
                               Model model) {
        List<User> list = userService.list();

        // 分页查询数据
        Page<User> userPage = new Page<>(pn, 3);
        // 分页查询结果
        Page<User> page = userService.page(userPage, null);

        model.addAttribute("page", page);
        return "index";
    }

    @RequestMapping("/user/delete/{id}")
    public String deleteUser(@PathVariable("id") Long id,
                             @RequestParam(value = "pn", defaultValue = "1") Integer pn,
                             RedirectAttributes ra){

        userService.removeById(id);

        // 页面重定向时添加pn参数
        ra.addAttribute("pn", pn);

        return "redirect:/";
    }

    @PostMapping("/user/add")
    public String addUser(User user, RedirectAttributes ra) {
        log.info("新增加了用户=====id:{},name:{},age:{},email:{}", user.getId(), user.getName(), user.getAge(), user.getEmail());
        userService.addUser(user);
        Page<User> page = userService.page(new Page<>(1, 3));
        ra.addAttribute("pn", page.getPages());
        return "redirect:/";
    }

    @PostMapping("/user/update/{pn}")
    public String updateUser(User user, RedirectAttributes ra,
                             @PathVariable("pn") int pn) {
        userService.updateById(user);
        ra.addAttribute("pn", pn);
        return "redirect:/";
    }

}
